<template>
  <div class="kzgl-statistics">
    <div class="statistic-navbar">
      <van-image
        width="20px"
        height="20px"
        fit="contain"
        :src="require('../assets/ic_arrow_left_black.png')"
        @click="closeStatistic" />
      <span class="statistic-navbar-title">矿政统计</span>
      <span>&nbsp;&nbsp;</span>
    </div>
    <CommonEcharts :options="lskstjChartData" />
    <CommonEcharts :options="kztjChartData" />
    <CommonEcharts class="ml-10" :options="barChartOptions" />
  </div>
</template>

<script>
import CommonEcharts from './CommonEcharts.vue'
import { getKsPieChart } from '@/api'
export default {
  components: { CommonEcharts },
  props: {
    chartData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      lskstjChartData: {},
      kztjChartData: {}
    }
  },
  computed: {
    // 优化后的barChartOptions，确保响应式更新
    barChartOptions() {
      // 处理空数据情况
      const safeChartData = this.chartData.length > 0 ? this.chartData : []

      return {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'axis',
          // 完全移除ECharts原生样式，只使用自定义HTML样式
          backgroundColor: 'transparent',
          borderWidth: 0,
          padding: 0,
          // 自定义tooltip显示格式
          formatter: function (params) {
            const data = params[0]
            return `
            <div class="custom-tooltip">
              <span class="font-14">${data.name}</span>
              <br/>
              <span class="font-12">${data.seriesName}: ${data.value}</span>
            </div>`
          }
        },
        grid: {
          left: 0,
          top: '5%',
          right: '2%',
          bottom: 0, // 增加底部空间，防止X轴标签重叠
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: safeChartData.map(item => item.xzqmc),
            axisTick: {
              alignWithLabel: true
            },
            // 美化X轴标签样式
            axisLabel: {
              color: '#666666',
              interval: 0,
              rotate: 40 // 可以根据需要设置旋转角度
            },
            axisLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.1)'
              }
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            axisLabel: {
              color: '#666666'
            },
            axisLine: {
              show: false
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(0, 0, 0, 0.1)',
                type: 'dashed' // 将y轴横线改为虚线
              }
            }
          }
        ],
        series: [
          {
            name: '背景',
            type: 'bar',
            barWidth: 20,
            tooltip: {
              show: false
            },
            data: safeChartData.map(() => {
              // 找到最大值作为背景高度
              const values = safeChartData.map(item => item.value)
              const maxValue = values.length > 0 ? Math.max(...values) : 100
              // 自动计算以0结尾的最大值（向上取整到最近的10的倍数）
              // 例如：45→50、145→150、12→20
              const roundedMaxValue = maxValue % 10 === 0 ? maxValue : Math.ceil(maxValue / 10) * 10

              return roundedMaxValue
            }),
            itemStyle: {
              color: '#82AEFF2B'
            },
            animationDuration: 1500
          },
          // 前景柱状图 - 宽度8，居中显示在背景上
          {
            name: '矿山数量',
            type: 'bar',
            barGap: '-70%',
            // barMaxWidth: 16,
            barWidth: 8,

            data: safeChartData.map(item => item.value),
            // 设置柱状图样式
            itemStyle: {
              // 使用echarts支持的颜色格式，不直接使用echarts实例
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: '#10A8D7' },
                  { offset: 1, color: 'rgba(3,158,210,0)' }
                ]
              },
              // 边框样式
              borderWidth: 1,
              borderType: 'solid',
              borderColor: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(151, 222, 246, 1)' },
                  { offset: 1, color: 'rgba(127, 227, 255, 0)' }
                ]
              }
            },
            // 添加动画效果
            animationDuration: 1500,
            // 鼠标移入时的样式
            emphasis: {
              itemStyle: {
                // 鼠标移入时的背景渐变色
                color: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: '#5FF5B5' },
                    { offset: 1, color: 'rgba(95,245,181,0)' }
                  ]
                },
                // 鼠标移入时的边框样式
                borderWidth: 1,
                borderType: 'solid',
                borderColor: {
                  type: 'linear',
                  x: 0,
                  y: 0,
                  x2: 0,
                  y2: 1,
                  colorStops: [
                    { offset: 0, color: 'rgba(152, 255, 115, 1)' },
                    { offset: 1, color: 'rgba(152, 255, 115, 0)' }
                  ]
                }
              }
            }
          }
        ]
      }
    }
  },
  created() {
    this.getKsPieData()
  },

  methods: {
    // 获取矿山饼状图统计
    getKsPieData() {
      getKsPieChart().then(res => {
        let { lskstj, kztj } = res.data

        this.lskstjChartData = this.initPieChart(lskstj, '绿色矿山')
        this.kztjChartData = this.initPieChart(kztj, '矿山总量')
      })
    },
    initPieChart(dataList, title) {
      let colors = ['#FF5089', '#FFB765', '#33A7FF', '#7FF6FA', '#D568FB', '#2066FE', '#00DBDB', '#FF4546', '#67C23A']

      dataList.forEach((item, index) => {
        item.itemStyle = { color: colors[index] }
        item.value = Number(item.value)
      })

      // 计算总量
      const totalCount = dataList.reduce((sum, item) => sum + item.value, 0)

      return {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'transparent',
          borderWidth: 0,
          padding: 0,
          formatter: function (params) {
            // 直接使用数据中的percentage字段，如果没有则计算
            const percentage = params.data?.percentage || ((params.value / totalCount) * 100).toFixed(0)
            return `
              <div class="custom-tooltip">
                <span class="font-14">${params.name}：</span>
                <br/>
                <span class="font-12">数量：${params.value}</span>
                <br/>
                <span class="font-12">占比：${percentage}</span>
              </div>`
          }
        },
        // 将graphic移到option根级别，确保中间文字正确显示
        graphic: [
          {
            type: 'text',
            left: 'center',
            top: '38%',
            style: {
              text: title,
              fontSize: 12,
              fill: 'rgba(0, 0, 0, 0.7)'
            }
          }
        ],
        series: [
          {
            name: '矿种分布',
            type: 'pie',
            radius: ['55%', '85%'],
            avoidLabelOverlap: false,
            itemStyle: {
              // borderRadius: 10,
              borderColor: 'rgba(0, 0, 0, 0.1)',
              borderWidth: 2
            },
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: false
              }
            },
            labelLine: {
              show: false
            },
            // 饼图中心位置
            center: ['50%', '50%'],
            data: dataList
          },

          {
            name: '中间文字',
            type: 'gauge',
            radius: ['50%', '80%'], // 需和type: 'pie'中的center一致
            // 配置中间的数字的样式
            detail: {
              // 调节数字位置
              offsetCenter: [-1, 12],
              fontSize: 20,
              color: '#666666'
            },
            // 中间的字和数字 数据
            data: [
              {
                value: totalCount,
                name: '',
                title: {
                  show: false
                }
              }
            ],
            pointer: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLine: {
              show: false
            },
            splitLine: {
              show: false
            },
            axisLabel: {
              show: false
            }
          }
        ]
      }
    },
    closeStatistic() {
      this.$emit('closeStatistic')
    }
  }
}
</script>

<style scoped>
.kzgl-statistics {
  background-color: #fff;
  display: flex;
  flex-direction: column;
}
.statistic-navbar {
  width: calc(100vw - 24px);
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 12px;
}
.statistic-navbar-title {
  font-weight: 800;
  font-size: 18px;
  color: #000;
}
.custom-tooltip {
  color: #ffffff;
  padding: 8px 16px;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.15);
  backdrop-filter: blur(20px);
}
.font-14 {
  font-size: 14px;
}
.font-12 {
  font-size: 12px;
}
</style>
